package com.jnshu.service.impl;

import com.aliyuncs.exceptions.ClientException;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jnshu.dao.UserMapper;
import com.jnshu.dto.user.UserDto;
import com.jnshu.dto.user.UserList;
import com.jnshu.dto.user.UserTo;
import com.jnshu.dto.user.UserVo;
import com.jnshu.pojo.User;
import com.jnshu.service.BackUserService;
import com.jnshu.tools.binding.*;
import com.jnshu.tools.resultUtils.RUtil;
import com.jnshu.tools.resultUtils.ResultBean;
import com.jnshu.tools.resultUtils.ResultEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;

/**
 * @ClassName BackUserServiceImpl
 * @Descrintion
 * @Author bd
 * @Date 2019/8/7 22:37
 * @Version 1.0
 **/
@Service
@Slf4j
public class BackUserServiceImpl implements BackUserService {

    @Autowired(required = false)
    UserMapper userMapper;

    //用户详情
    @Override
    public ResultBean selectByPrimaryKey(long id) {
        log.info("传入需要查询用户的id为" + id);
        try {
            User user = userMapper.selectByPrimaryKey(id);
            log.info("查询用户的user为" + user);
            UserDto userDto = new UserDto();
            BeanUtils.copyProperties(user, userDto);

            if (userDto == null) {
                return RUtil.error(401, "用户信息不存在");
            } else {
                return RUtil.ok(userDto);
            }
        } catch (Exception e) {
            return RUtil.error(300, "请求id不存在");
        }

    }

    //用户列表
    @Override
    public ResultBean selectList(UserVo userVo, int pageSize, int pageNum) {
        log.info("查询列表的参数" + userVo + ",每页数量为" + pageSize + ",页码为" + pageNum);
        UserTo user = new UserTo();
        log.info("============+" + userVo.getEmailStatus());
        if (userVo.getEmailStatus() == null) {

            user.setGrade(userVo.getGrade());
            user.setNickname(userVo.getNickname());
            user.setStatus(userVo.getStatus());
            user.setEmail(null);
            user.setStartTime(userVo.getStartTime());
           user.setEndTime(userVo.getEndTime());



        } else if (userVo.getEmailStatus() == 0) {
            user.setGrade(userVo.getGrade());
            user.setNickname(userVo.getNickname());
            user.setStatus(userVo.getStatus());
            user.setEmail("0");
            user.setStartTime(userVo.getStartTime());
            user.setEndTime(userVo.getEndTime());
        } else {
            user.setGrade(userVo.getGrade());
            user.setNickname(userVo.getNickname());
            user.setStatus(userVo.getStatus());
            user.setEmail("1");
            user.setStartTime(userVo.getStartTime());
            user.setEndTime(userVo.getEndTime());
        }
        log.info("user======="+user);
        PageHelper.startPage(pageNum, pageSize);
        List<UserList> userList = userMapper.selectUserList(user);
        log.info("查询出的信息为" + userList);
        PageInfo<UserList> info = new PageInfo<>(userList);
        log.info("分页后的信息为" + info);
        if (info == null) {
            return RUtil.error(401, "用户信息不存在");
        } else {
            return RUtil.ok(info);
        }
    }

    /**
     * 发送手机验证码
     * @param phone
     * @return
     */
    @Override
    public ResultBean sendPhoneCode(String phone) throws ClientException {
        log.info("person controller传过来的手机号码为："+phone);
        User user = userMapper.selectByPhone(phone);
        if (!RegularUtil.isPhone(phone)){
            log.error("手机号码不符法");
            return RUtil.error(504,"手机号码不合法");
        }//两个phone作为key是为了防止被覆盖
        if (PastDueUtil.pastDue(phone+phone) > 3){
            log.error("验证码获取次超过3次");
            return RUtil.error(505,"验证码获取次数过多，请明天再次尝试");
        }//判断手机号码是否为空
        if (phone.equals("")){
            log.error("手机号码为空");
            return RUtil.error(506,"手机号码不能为空");
        }//判断手机号码是否已存在
        if (user != null){
            log.error("手机号码已绑定");
            return RUtil.error(507,"手机号码已绑定用户，请更换手机号码");
        }//生成验证码
        String code = RandomCode.randomTwo();
        log.info("绑定的手机号码为："+phone+",验证码为："+code);
        //将手机号码-验证码以key-value放入redis中用于验证
        RedisUtil.setObject(phone,code);
        //设置过期时间设为10分钟
        RedisUtil.cacheExpire(phone,60*5);
        //发送手机验证码
        AliSmsUtil.sendSms(phone,code);
        return RUtil.ok("验证码发送成功");
    }

    @Override
    public ResultBean bindingPhone(String phone, String code, long id) {
        log.info("person controller传过来的手机号码为："+phone+",code为："+code);
        if (!RegularUtil.isPhone(phone)){
            return RUtil.error(ResultEnum.PHONE_ERROR);
        }//获取缓存中的code验证码
        String verifyCode = (String) RedisUtil.getObject(phone);
        log.info("缓存中的验证码是："+verifyCode);
        if (verifyCode != null && verifyCode.equals(code)){
            log.info("验证码正确，更新用户表手机号信息");
            User user = userMapper.selectByPrimaryKey(id);
            log.info("绑定手机的用户为："+user);
            //将获取到的手机号码设置到数据表中去
            user.setPhone(phone);
            //修改用户更新时间
            user.setUpdateAt(System.currentTimeMillis());
            //将修改后的user写入数据库中
            userMapper.updateByPrimaryKeySelective(user);
            log.info("绑定手机号码后的用户："+user);
            return RUtil.ok();
        }
        return RUtil.error(ResultEnum.CODE_ERROR);
    }

    @Override
    public ResultBean sendEmailCode(String email) throws IOException {
        log.info("person controller传过来的邮箱地址为："+email);
        User user = userMapper.selectByEmail(email);
        if (!RegularUtil.isEmail(email)){
            log.error("邮箱地址不合法");
            return RUtil.error(504,"邮箱地址错误");
        }//两个email为key是为了防止被覆盖
        if (PastDueUtil.pastDue(email+email) >3){
            log.error("验证次数超过3次");
            return RUtil.error(505,"验证码获取次数过多，请明天再次尝试");
        }//判断邮箱地址是否为空
        if (email.equals("")){
            log.error("邮箱地址为空");
            return RUtil.error(506,"邮箱地址不能为空");
        }//判断邮箱是否以存在
        if (user != null){
            log.error("邮箱已绑定");
            return RUtil.error(507,"邮箱已被绑定，请更换邮箱地址");
        }//生成验证码
        String code = RandomCode.randomTwo();
        log.info("绑定的手机号码为："+email+",验证码为："+code);
        //将邮箱地址-验证码以key-value放入redis中用于验证
        RedisUtil.setObject(email,code);
        //设置过期时间设为5分钟
        RedisUtil.cacheExpire(email,60*5);
        //发送验证码
        EmailUtil.sendEmail(email,code);
        return RUtil.ok();
    }

    @Override
    public ResultBean bindingEmail(String email, String code, long id) {
        log.info("person controller传过来的手机号码为："+email+",code为："+code);
        if (!RegularUtil.isEmail(email)){
            log.error("邮箱地址错误");
            return RUtil.error(ResultEnum.EMAIL_ERROR);
        }//获取缓存中的邮箱验证码
        String verifyCode = (String)RedisUtil.getObject(email);
        log.info("缓存中的验证码是："+verifyCode);
        if (verifyCode != null && verifyCode.equals(code)){
            log.info("验证码正确，更新用户表号信息和积分信息");
            User user = userMapper.selectByPrimaryKey(id);
            log.info("绑定邮箱用户："+user);
            String userEmail = user.getEmail();
            if (userEmail == null){
                log.info("该用户邮箱第一次绑定,更新用户表邮箱信息和积分信息");
                user.setEmail(email);
                //同时更新用户的积分以及更新时间
                user.setIntegral(user.getIntegral()+5);
                user.setUpdateAt(System.currentTimeMillis());
                userMapper.updateByPrimaryKeySelective(user);
                log.info("用户更新后的信息："+user);
                return RUtil.ok();
            }else if (userEmail.equals(email)){
                log.info("邮箱已绑定");
                return RUtil.ok(ResultEnum.EMAIL_BINDING);
            }else {
                log.info("用户不是首次绑定邮箱");
                return RUtil.ok();
            }
        }
        return RUtil.error(ResultEnum.CODE_ERROR);
    }
}
